/**
 * KafkaConsumerOperatorMain.java
 *
 * @author: ZhuJiahui
 * @date: 2019/1/11 20:55
 */
package com.zhujiahui.kafka.first;

import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

/**
 * @description:
 * @author: ZhuJiahui
 * @version: 1.0
 */
public class KafkaConsumerOperatorMain {
    public static void main(String[] args) throws IOException {
        Properties properties = new Properties();
        InputStream in = KafkaConsumerOperatorMain.class.getClassLoader()
                .getResourceAsStream("consumer.properties");
        properties.load(in);

        Consumer<String, String> consumer = new KafkaConsumer<>(properties);
        List<String> topicList = Arrays.asList("sbkafka");

        // 消费者订阅topic
        consumer.subscribe(topicList);

        ConsumerRecords<String, String> consumerRecords = null;

        while (true) {
            // 从topic中拉去数据
            consumerRecords = consumer.poll(1000);
            // 遍历
            for (ConsumerRecord consumerRecord : consumerRecords) {
                long offset = consumerRecord.offset();
                int partition = consumerRecord.partition();
                Object key = consumerRecord.key();
                Object value = consumerRecord.value();
                System.out.format("%d\t%d\t%s\t%s\n", offset, partition, key,
                        value);
            }
        }

    }
}
